import numpy as np
from numpy.ma.core import floor

def chose_operator(chrom: np.ndarray, chrom_format, method_type: int, get_number=None) -> tuple[np.ndarray, np.ndarray]:
    if method_type == 1:  # 基本的排序算法
        sorted_indices = np.argsort(chrom[:, chrom_format[1]])
        sorted_chrom = chrom[sorted_indices, :]  # 对选中的种群进行排序
        chrom_selected = sorted_chrom[0:get_number, :]
        chrom_left = sorted_chrom[get_number:, :]
        return chrom_selected, chrom_left
    else:
        pass

def cross_operator(chromA: np.ndarray, chromB: np.ndarray, chrom_format) -> np.ndarray:
    cross_position = np.random.randint(1, chrom_format[0], size=chromA.shape[0])
    crossed_chrom = np.empty((chromA.shape[0], chrom_format[0] + 1))
    for i in range(chromA.shape[0]):
        new_individual = chromA[i, 0:cross_position[i]]
        individual_pos_to_get = chromA[i, cross_position[i]:chrom_format[0] + 1]
        for j in chromB[i, 0:chrom_format[0] + 1]:
            if np.isin(j, individual_pos_to_get).any():
                new_individual = np.hstack((new_individual, j))
            else:
                pass
        crossed_chrom[i, :] = new_individual
    return crossed_chrom

def mutate_operator(chrom: np.ndarray, chrom_format, mutate_pos_num: int) -> np.ndarray:
    mutate_position = np.random.randint(1, chrom_format[0] - mutate_pos_num, size=chrom.shape[0])
    mutated_chrom = np.empty((chrom.shape[0], chrom_format[0] + 1))
    for i in range(chrom.shape[0]):
        new_individual = chrom[i, 0:mutate_position[i]]
        new_individual = np.hstack((new_individual, chrom[i, mutate_position[i] + mutate_pos_num - 1:mutate_position[i] - 1:-1]))
        new_individual = np.hstack((new_individual, chrom[i, mutate_position[i] + mutate_pos_num:chrom_format[0] + 1]))
        mutated_chrom[i, :] = new_individual
    return mutated_chrom
